<?php

namespace Glpmr\QuizzBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Glpmr\QuizzBundle\Entity\Quizz;
use Glpmr\QuizzBundle\Form\QuizzType;
use Glpmr\QuizzBundle\Entity\Promotion;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller {

    public function indexAction() {
        return $this->render('GlpmrQuizzBundle:Default:index.html.twig');
    }

    /**
     * @Security("has_role('ROLE_ADMIN')")
     */
    public function ajouterAction() {
        $unQuizz = new Quizz();
        $promotions = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Promotion')->findAll();

        $form = $this->createFormBuilder($unQuizz)
                ->add("titre", "text")
                ->add("description", "textarea")
                ->add("promotion", "entity", array(
                    "label" => "Promotion",
                    "class" => 'GlpmrQuizzBundle:Promotion',
                ))
                //->add("etat", "checkbox", array("required" => false))
                ->getForm();

        // On traite le formulaire
        $request = $this->get('request');
        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            if ($form->isValid()) {

                $quizz = $form->getData();
                $quizz->setDateCreation(date_create(date("Y-m-d")));

                $data = $request->request->get('etat');
                if (null == $data) {
                    $quizz->setEtat(0);
                } else {
                    $quizz->setEtat(1);
                }
                $em = $this->getDoctrine()->getManager();
                $em->persist($quizz);
                $em->flush();

                $url = $this->generateUrl("glpmr_quizz_lister");
                return $this->redirect($url);
            } else {
                throw $this->createNotFoundException('Le formulaire n\'est pas valide' . var_dump($form->getErrorsAsString()));
            }
        } else {
            return $this->render('GlpmrQuizzBundle:Default:ajouter.html.twig', array("form" => $form->createView(), "promotions" => $promotions));
        }
    }

    public function listerAction() {
        $quizz = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Quizz')->findAll();
        $promotions = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Promotion')->findAll();

        if (!$quizz) {
            throw $this->createNotFoundException('Aucun quizz en base de données');
        } else {
            return $this->render('GlpmrQuizzBundle:Default:listQuizz.html.twig', array("listQuizz" => $quizz, "promotions" => $promotions));
        }
    }

    public function modifierAction($id) {
        $quizz = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Quizz')->findOneById($id);
        $promotions = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Promotion')->findAll();

        if (!$quizz) {
            throw $this->createNotFoundException('Aucun quizz en base de donn&eacute;es');
        } else {
            $request = $this->get('request');
            if ($request->getMethod() == 'POST') {
                $data = $request->request->all();

                $titre = $data["titre"];
                $description = $data["description"];
                $libelle = $data["promotion"];
                $promotion = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Promotion')->findOneBy(array('libelle' => $libelle));
                if (isset($data["etat"])) {
                    $etat = $data["etat"];
                    if ($etat == "on") {
                        $etat = true;
                    }
                } else {
                    $etat = false;
                }
                $quizz->setEtat($etat);

                // On met à jour le quizz récupéré au début
                $quizz->setTitre($titre);
                $quizz->setDescription($description);
                $quizz->setPromotion($promotion);


                $em = $this->getDoctrine()->getManager();
                $em->persist($quizz);
                $em->flush();

                $url = $this->generateUrl("glpmr_quizz_lister");
                return $this->redirect($url);
            } else {
                return $this->render('GlpmrQuizzBundle:Default:modifierQuizz.html.twig', array("quizz" => $quizz, "promotions" => $promotions));
            }
        }
    }

    public function supprimerAction($id) {
        $quizz = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Quizz')->findOneById($id);
        $em = $this->getDoctrine()->getManager();
        $em->remove($quizz);
        $em->flush();

        $url = $this->generateUrl("glpmr_quizz_lister");
        return $this->redirect($url);
    }

    public function afficherAction() {
        $currentEleve = $this->get('security.context')->getToken()->getUser();
        $listQuizz;

        if ($this->get('security.context')->isGranted("ROLE_ADMIN")) {
            // On affiche tout les quizz à l'admin
            $listQuizz = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Quizz')->findAll();
        } else {
            // On affiche que ceux de la promo
            $idPromotion = $currentEleve->getPromotion()->getId();
            $em = $this->getDoctrine()->getManager();
            $listQuizz = $em->getRepository('GlpmrQuizzBundle:Quizz')->createQueryBuilder('q')->join('q.promotion', 'p')->where("p.id = $idPromotion")->getQuery()->getResult();
        }



        return $this->render('GlpmrQuizzBundle:Default:afficherQuizz.html.twig', array("listQuizz" => $listQuizz));
    }

}
